package com.example.hcd.functionactivity;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.message.BasicNameValuePair;
import org.jsoup.Jsoup;

import com.example.hcd.MenuActivity;
import com.example.hcd.R;
import com.example.hcd.adapt.ImageAndTextListAdapter;
import com.example.hcd.datamanage.ImageAndText;
import com.example.hcd.datamanage.JPushMessage;
import com.example.hcd.datamanage.NoticeData;
import com.example.hcd.internet.FileUtils;
import com.example.hcd.internet.InternetKeep;
import com.example.hcd.internet.LinkHelp;
import com.example.hcd.internet.URLS;
import com.example.hcd.tool.Constants;
import com.example.hcd.tool.MyGridView;
import com.example.hcd.tool.NoticeDetailView;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class NoticeDetailActivity extends BaseActivity implements OnItemClickListener, OnClickListener {
    private int num;
    private NoticeData noticeData;
    private ImageAndTextListAdapter adapter;
    private boolean shouldFresh = false;
    List<ImageAndText> listImageAndText;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        mPageName = "NoticeDetailActivity";
        setContentView(R.layout.noice_detail_view);
        if (!getIntent().hasExtra(Constants.NOTIFICATION)) {
            shouldFresh = getIntent().getBooleanExtra("should_refresh", shouldFresh);
            num = Integer.parseInt(getIntent().getStringExtra("NOTICE_NUM"));
            noticeData = InternetKeep.getInstence().getNoticeList().get(num - 1);
        } else {
            JPushMessage mNotification = (JPushMessage) getIntent().getSerializableExtra(Constants.NOTIFICATION);
            shouldFresh = true;
            noticeData = new NoticeData();
            noticeData.setContent(mNotification.getContent());
            noticeData.setTitle(mNotification.getTitle());
            noticeData.setCreate_time(mNotification.getCreate_time());
            noticeData.setCreate_by(mNotification.getCreate_by());
            noticeData.setImgPrefix(mNotification.getImgPrefix());

            if (!"".equals(mNotification.getImgs()) && null != mNotification.getImgs()) {
                String[] imgs = mNotification.getImgs().split(",");
                for (int i = 0; i < imgs.length; i++) {
                    String textName = imgs[i].toString();
                    if (FileUtils.isPic(textName)) {
                        noticeData.getPicList().add(textName);
                    } else {
                        noticeData.getFileList().add(textName);
                    }

                }
            }

        }


        if (!shouldFresh) {
            NoticeDetailActivity.this.setResult(Activity.RESULT_CANCELED, getIntent());
        } else {
            NoticeDetailActivity.this.setResult(Activity.RESULT_OK, getIntent());
        }

        initView();

        ImageView leftBtn = (ImageView) findViewById(R.id.title_bar_btn_left);
        leftBtn.setOnClickListener(this);
    }

    private void initView() {
        TextView title = (TextView) findViewById(R.id.title);
        title.setText(noticeData.getTitle());

        TextView time = (TextView) findViewById(R.id.title2);
        time.setText("发布时间:" + noticeData.getCreate_time());

        TextView people = (TextView) findViewById(R.id.title3);
        people.setText("发布人:" + noticeData.getCreate_by());
        RelativeLayout noticeDetail = (RelativeLayout) findViewById(R.id.detail);
//		mWebView = (WebView) findViewById(R.id.textinfomore);

        ArrayList<String> imgList = new ArrayList<String>();
        ArrayList<String> textList = new ArrayList<String>();
        org.jsoup.nodes.Document doc = Jsoup.parse(noticeData.getContent());

        org.jsoup.select.Elements links_source = doc.getElementsByTag("p");
        for (int i = 0; i < links_source.size(); i++) {
            textList.add(links_source.get(i).text().toString());
        }

        org.jsoup.select.Elements links = doc.getElementsByTag("img");
        for (int i = 0; i < links.size(); i++) {
            imgList.add(links.get(i).attr("src").toString());
        }

        NoticeDetailView detailView = new NoticeDetailView(this, textList, imgList);
        noticeDetail.addView(detailView, new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        noticeDetail.requestLayout();
        //
        // content.setText(doc.body().text());
//		WebSettings webSettings = mWebView.getSettings();
//		webSettings.setDefaultTextEncodingName("utf-8");
//
//		// User settings
//
//		webSettings.setJavaScriptEnabled(true);
//		webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
//		webSettings.setUseWideViewPort(true);// 关键点
//
//		webSettings.setDisplayZoomControls(false); // 设置支持javascript脚本
//		webSettings.setAllowFileAccess(true); // 允许访问文件
//		webSettings.setBuiltInZoomControls(true); // 设置显示缩放按钮
//		webSettings.setSupportZoom(true); // 支持缩放
//
//		webSettings.setLoadWithOverviewMode(true);
//
//		/**
//		 * 用WebView显示图片，可使用这个参数 设置网页布局类型： 1、LayoutAlgorithm.NARROW_COLUMNS ：
//		 * 适应内容大小 2、LayoutAlgorithm.SINGLE_COLUMN:适应屏幕，内容将自动缩放
//		 */
//		webSettings.setLayoutAlgorithm(LayoutAlgorithm.NARROW_COLUMNS);
//
//		String linkJs = "<script type=\"text/javascript\" src=\"file:///android_asset/resizeimg.js\"></script>";
//
//		mWebView.setWebViewClient(new MyWebViewClient());
//
//		mWebView.loadDataWithBaseURL(null, noticeData.getContent() + linkJs, "text/html", "utf-8", null);
        // mWebView.loadData(linkJs+noticeData.getContent(), "text/html;
        // charset=UTF-8", null);

        MyGridView gridview = (MyGridView) findViewById(R.id.file_gridview);
        // 实力化几个ImageAndText 对象
        listImageAndText = new ArrayList<ImageAndText>();
        for (int i = 0; i < noticeData.getPicList().size(); i++) {
            ImageAndText iat = new ImageAndText(noticeData.getImgPrefix() + noticeData.getPicList().get(i),
                    noticeData.getImgPrefix()+noticeData.getPicList().get(i));
            listImageAndText.add(iat);
        }
        for (int i = 0; i < noticeData.getFileList().size(); i++) {
            ImageAndText iat = new ImageAndText(noticeData.getImgPrefix()+noticeData.getFileList().get(i), noticeData.getImgPrefix()+noticeData.getFileList().get(i));
            listImageAndText.add(iat);
        }

        if (listImageAndText.size() == 0) {
            findViewById(R.id.appendix_bg).setVisibility(View.GONE);
        }

        adapter = new ImageAndTextListAdapter(NoticeDetailActivity.this, listImageAndText, gridview);
        gridview.setAdapter(adapter);

        gridview.setOnItemClickListener(this);

        LoadTaskInfoList load = new LoadTaskInfoList();
        load.execute();
    }


    private class LoadTaskInfoList extends AsyncTask<String, Integer, String> {

        public LoadTaskInfoList() {
        }

        @Override
        protected void onPreExecute() {
        }

        @Override
        protected String doInBackground(String... params) {
            String result = null;
            HttpResponse response = null;
            BufferedReader reader = null;
            try {
                ArrayList<NameValuePair> vs = new ArrayList<NameValuePair>();
                // vs.add(new BasicNameValuePair("taskId", taskId));
                vs.add(new BasicNameValuePair("notificationId", noticeData.getId()));
                response = LinkHelp.post(URLS.getReadNotice(), vs, false);
                // System.out.println(URLS.getTaskInfoByType(type));
                if (response != null) {
                    StatusLine line = response.getStatusLine();
                    if (line.getStatusCode() == 200) {
                        reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                        StringBuilder sb = new StringBuilder();
                        for (String s = reader.readLine(); s != null; s = reader.readLine()) {
                            sb.append(s);
                        }
                        result = sb.toString();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (reader != null) {
                    try {
                        reader.close();

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return result;
        }

        @Override
        protected void onPostExecute(String result) {

            if (!TextUtils.isEmpty(result)) {
                if (result.contains("success")) {
                    {
                        // //首页任务状态刷新
                        // Intent mIntent = new
                        // Intent(MenuActivity.RECRIVE_BROADCAST);
                        // //发送广播
                        // sendBroadcast(mIntent);

                        MenuActivity.sendMsg();

                        if (shouldFresh) {
                            NoticeDetailActivity.this.setResult(Activity.RESULT_OK, getIntent());
                        }

                    }

                } else {
                    NoticeDetailActivity.this.setResult(Activity.RESULT_CANCELED, getIntent());
                }

            } else {
                NoticeDetailActivity.this.setResult(Activity.RESULT_CANCELED, getIntent());
            }

        }

    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        // TODO Auto-generated method stub
        ImageAndText uri = adapter.getItem(arg2);
        System.out.println(uri.getText());

        if (FileUtils.isPic(uri.getText())) {
            ArrayList<String> picpathlist = new ArrayList<String>();
            Intent intent = new Intent(NoticeDetailActivity.this, ShowPictureList.class);
            for (int i = 0; i < listImageAndText.size(); i++) {
                if (FileUtils.isPic(listImageAndText.get(i).getText())) {
                    picpathlist.add(listImageAndText.get(i).getImageUrl());
                }
            }

            for (int i = 0; i < picpathlist.size(); i++) {
                if (picpathlist.get(i).equals(uri.getText())) {
                    intent.putExtra("MOREN_INDEX", i);
                    intent.putExtra("", 1);
                }
            }

            intent.putStringArrayListExtra("PICK_PATH_LIST", picpathlist);

            intent.putExtra("IS_BENDI", false);
            startActivity(intent);
        } else {
            Intent intent = new Intent(NoticeDetailActivity.this, FileDetailActivity.class);
            intent.putExtra("FILE_URI", uri.getText());
            intent.putExtra("FILE_NAME", uri.getText());
            startActivity(intent);
        }

        overridePendingTransition(R.anim.out_alpha, R.anim.enter_alpha);

    }


    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub
        int id = arg0.getId();
        switch (id) {
            case R.id.title_bar_btn_left:
                finish();
                break;

            default:
                break;
        }
    }
}
